import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '../views/index/index'//首页
import Login from '../components/login'//登录
import CourseDetails from "../views/courseDetails/courseDetails"//课程详情
import PersonalCenter from "../views/Personal/personalCenter";//个人中心
import Search from "../views/search"//搜索页
import Vuex  from "../components/vuex"
// import store from  "../store/index"
import {viewUserInfo} from "../api/login";
Vue.use(VueRouter)

const routes = [
  {
    path:'/',
    redirect:'/index'
  },
  {
    path: '/index',//首页
    component: Index,
    name:"Index"
  },
  {
    path: '/login',//登录页
    component: Login,
  },
  {
    path: '/courseDetails',//课程详情页
    component:CourseDetails,
  },
  {
    path: '/personalCenter',//个人中心页
    component:PersonalCenter,
    name:"PersonalCenter",
    meta:{
      needLogin:true,
    }

  },
  {
    path: '/search',//搜素页
    component:Search,
  },
    //练习vuex
  {
    path: '/vuex',//练习
    name:'Vuex',
    component:Vuex,
  },
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//创建一个前置路由
router.beforeEach((to,from,next)=>{
  if(to.meta.needLogin==true) {
    // 判断用户是否登录
    viewUserInfo().then(res=>{
      console.log(res)
      if(res.code==0) {
        next();
      } else {
        next({path:"/index",query:{dialog:true}})
      }
    })

  }
  else {
    next()
  }
  // console.log(to);
  // console.log(from);
  // console.log(next);
  // next();

})
export default router
